package cn.com.do1.component.moblie.moblie.ui;

import cn.com.do1.common.dac.Pager;
import cn.com.do1.common.annotation.struts.*;
import cn.com.do1.common.exception.IllegalParameterException;
import cn.com.do1.common.framebase.struts.BaseAction;
import cn.com.do1.common.util.DateUtil;
import cn.com.do1.component.excelUtil.util.ExcelUtil;
import cn.com.do1.component.moblie.moblie.model.*;
import cn.com.do1.component.moblie.moblie.service.IMoblieService;
import cn.com.do1.component.moblie.moblie.service.impl.ExcelService;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import cn.com.do1.common.exception.BaseException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.SQLException;

import cn.com.do1.common.util.AssertUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copyright &copy; 2010 广州市道一信息技术有限公司
 * All rights reserved.
 * User: ${user}
 */
public class MoblieAction extends BaseAction {
    private final static transient Logger logger = LoggerFactory.getLogger(MoblieAction.class);
    private IMoblieService moblieService;
    private TbMoblieDataPO tbMoblieDataPO;
    private String ids[];
    private String id;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    private File file;
    private String fileFileName;

    public IMoblieService getMoblieService() {
        return moblieService;
    }

    @Resource
    public void setMoblieService(IMoblieService moblieService) {
        this.moblieService = moblieService;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(
            nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "testNumber", type = "number"),
            @SearchValueType(name = "testString", type = "string", format = "%%%s%%")
    })
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        pager = moblieService.searchMoblie(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(
            nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "testNumber", type = "number"),
            @SearchValueType(name = "testString", type = "string", format = "%%%s%%")
    })
//    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxPortalSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        pager = moblieService.searchMoblie(getSearchValue(), pager);
        JSONObject json = new JSONObject();
        json.put("Total", pager.getTotalRows());
        if (AssertUtil.isEmpty(pager.getPageData())) {
            pager.setPageData(new ArrayList<TbMoblieDataPO>());
        }
        json.put("Rows", pager.getPageData());
        super.outString(json.toString());
    }

    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "新增成功", faileMsg = "新增失败"))
    public void ajaxAdd() throws Exception, BaseException {
        //todo:完成新增的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1003", successMsg = "更新成功", faileMsg = "更新失败"))
    public void ajaxUpdate() throws Exception, BaseException {
        //todo:完成更新的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "删除成功", faileMsg = "删除失败"))
    public void ajaxBatchDelete() throws Exception, BaseException {
        //完成批量更新的代码
    }

    public void setTbMoblieDataPO(TbMoblieDataPO tbMoblieDataPO) {
        this.tbMoblieDataPO = tbMoblieDataPO;
    }

    public TbMoblieDataPO setTbMoblieDataPO() {
        return this.tbMoblieDataPO;
    }

    public void addTbMoblieDataPO() {
        super.ajaxAdd(tbMoblieDataPO);
    }

    public void updateTbMoblieDataPO() {
        super.ajaxUpdate(tbMoblieDataPO);
    }

    public void deleteTbMoblieDataPO() {
        if (AssertUtil.isEmpty(id))
            id = ids[0];
        tbMoblieDataPO._setPKValue(id);
        super.ajaxDelete(tbMoblieDataPO);
    }

    public void batchDeleteTbMoblieDataPO() {
        super.ajaxBatchDelete(TbMoblieDataPO.class, ids);
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxView() throws Exception, BaseException {
        TbMoblieDataPO xxPO = moblieService.searchByPk(TbMoblieDataPO.class, id);
        addJsonFormateObj("tbMoblieDataPO", xxPO);//注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
    }

    public TbMoblieDataPO getTbMoblieDataPO() {
        return this.tbMoblieDataPO;
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "导入成功", faileMsg = "导入失败"))
    public void importExcel() throws BaseException {
        if (file == null) {
            throw new BaseException("传入了一个空文件");
        }

        if (!fileFileName.endsWith(".xls") && !fileFileName.endsWith(".xlsx")) {
            throw new BaseException("文件格式不对");
        }

        DataInputStream e = null;
        try {
            e = new DataInputStream(new FileInputStream(file));
        } catch (FileNotFoundException e1) {
            throw new BaseException("文件出错");
        }
        try {
            if ((long) e.available() > ExcelUtil.fileMaxSize) {
                throw new BaseException("文件太大");
            }
        } catch (IOException e1) {
            throw new BaseException("文件出错");
        }
        List<TbMoblieDataPO> list = ExcelUtil.importForExcel(file, fileFileName, TbMoblieDataPO.class, new ExcelService());

        if (!AssertUtil.isEmpty(list)) {

            for (int i = 0; i < list.size(); i++) {
                TbMoblieDataPO moblieDataPO = list.get(i);
                try {
                    moblieService.insertPO(moblieDataPO,true);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(
            nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "testNumber", type = "number"),
            @SearchValueType(name = "testString", type = "string", format = "%%%s%%")
    })
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    public String export() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), 9999999);
        List<TbMoblieDataPO> list = null;
        pager = moblieService.searchMoblie(getSearchValue(), pager);
        list = (List<TbMoblieDataPO>) pager.getPageData();

        if (!AssertUtil.isEmpty(list)) {

            // 调用导出方法，获取导出的文件
            String[] head = {"操作类型", "订单日期", "赠送日期", "手机号码", "分配的流量", "生效方式", "生效周期", "订单状态", "新增的套餐", "修改的套餐", "删除的套餐"};
            File excelFile = ExcelUtil.exportForExcel(head, list, TbMoblieDataPO.class);
            // 以流的形式输出导出的文件
            try {
                if (excelFile.exists()) {
                    String fileName = "手机充值信息" + DateUtil.formartCurrentDate() + ".xls";
                    InputStream is = new FileInputStream(excelFile);
                    HttpServletResponse response = ServletActionContext.getResponse();
                    OutputStream os = response.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                    response.reset();
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/ vnd.ms-excel");// 不同类型的文件对应不同的MIME类型

                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                    }
                    bos.flush();
                    bis.close();
                    bos.close();
                    is.close();
                    os.close();
                }
            } catch (Exception e) {
                logger.error("导入excel出错", e);
            }
        }

        return null;
    }

}
